/*
    Sean Austin. RCOS User Interface Research. Encapsulate 
    Copyright (C) <2011>  <Sean Austin>
    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

package com.rcos.ui;

import java.io.ByteArrayInputStream;
import java.net.MalformedURLException;
import java.net.URL;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import com.rcos.ui.views.SingleWeatherInfoView;
import com.rcos.ui.weather.GoogleWeatherHandler;
import com.rcos.ui.weather.WeatherCurrentCondition;
import com.rcos.ui.weather.WeatherForecastCondition;
import com.rcos.ui.weather.WeatherSet;
import com.rcos.ui.weather.WeatherUtils;

import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

public class WeatherForecast extends Activity {

	// Debug tag and checkbox that sets box if it is checked
	private final String DEBUG_TAG = "WeatherForcaster";
	private CheckBox chk_usecelsius = null;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.main);
		// Disable Theme
		//setTheme(android.R.style.Theme_Dark);

		this.chk_usecelsius = (CheckBox) findViewById(R.id.chk_usecelsius);

		Button cmd_submit = (Button) findViewById(R.id.cmd_submit);
		cmd_submit.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				URL url;
				try {
					/* Get what user typed to the EditText. */
					String cityParamString = ((EditText) findViewById(R.id.edit_input))
							.getText().toString();
					String queryString = "http://www.google.com/ig/api?weather="
							+ cityParamString;
					/* Replace blanks with HTML-Equivalent. */
					//url = new URL(queryString.replace(" ", "%20"));
					//url = new URL("http://www.google.com/ig/api?weather=Schriesheim,Germany");

					/* Get a SAXParser from the SAXPArserFactory. */
					SAXParserFactory spf = SAXParserFactory.newInstance();
					SAXParser sp = spf.newSAXParser();

					/* Get the XMLReader of the SAXParser we created. */
					XMLReader xr = sp.getXMLReader();

					/*
					 * Create a new ContentHandler and apply it to the
					 * XML-Reader
					 */
					GoogleWeatherHandler gwh = new GoogleWeatherHandler();
					xr.setContentHandler(gwh);

					/* Parse the xml-data our URL-call returned. */
					//xr.parse(new InputSource(url.openStream()));
                    
					/* Use HTTPClient to deal with the URL */
        			HttpClient httpclient = new DefaultHttpClient();
        			HttpGet httpget = new HttpGet(queryString.replace(" ", "%20"));
        			Log.d(DEBUG_TAG, "executing request " + httpget.getURI());
        			// create a response handler
        			ResponseHandler<String> responseHandler = new BasicResponseHandler();
        			String responseBody = httpclient.execute(httpget, responseHandler);
        			// Log.d(DEBUG_TAG, "response from httpclient:n "+responseBody);
        			
        			ByteArrayInputStream is = new ByteArrayInputStream(responseBody.getBytes());
        			xr.parse(new InputSource(is));
        			Log.d(DEBUG_TAG, "parse complete");
        			// parse complete

					/* Our Handler now provides the parsed weather-data to us. */
					WeatherSet ws = gwh.getWeatherSet();

					/* Update the SingleWeatherInfoView with the parsed data. */
					updateWeatherInfoView(R.id.weather_today, ws
							.getWeatherCurrentCondition());

					updateWeatherInfoView(R.id.weather_1, ws
							.getWeatherForecastConditions().get(0));
					updateWeatherInfoView(R.id.weather_2, ws
							.getWeatherForecastConditions().get(1));
					updateWeatherInfoView(R.id.weather_3, ws
							.getWeatherForecastConditions().get(2));
					updateWeatherInfoView(R.id.weather_4, ws
							.getWeatherForecastConditions().get(3));

				} catch (Exception e) {
					resetWeatherInfoViews();
					Log.e(DEBUG_TAG, "WeatherQueryError", e);
				}
			}
		});
	}

	private void updateWeatherInfoView(int aResourceID,
			WeatherForecastCondition aWFIS) throws MalformedURLException {
		
		/* Construct the Image-URL. */
		
		URL imgURL = new URL("http://www.google.com" + aWFIS.getIconURL());
		((SingleWeatherInfoView) findViewById(aResourceID)).setRemoteImage(imgURL);
		

		int tempMin = aWFIS.getTempMinCelsius();
		int tempMax = aWFIS.getTempMaxCelsius();

		/* Convert from Celsius to Fahrenheit if necessary. */
		if (this.chk_usecelsius.isChecked()) {
			((SingleWeatherInfoView) findViewById(aResourceID))
					.setTempCelciusMinMax(tempMin, tempMax);
		} else {
			tempMin = WeatherUtils.celsiusToFahrenheit(tempMin);
			tempMax = WeatherUtils.celsiusToFahrenheit(tempMax);
			((SingleWeatherInfoView) findViewById(aResourceID))
					.setTempFahrenheitMinMax(tempMin, tempMax);
		}
	}

	private void updateWeatherInfoView(int aResourceID,
			WeatherCurrentCondition aWCIS) throws MalformedURLException {
		
		/* Construct the Image-URL. */
		
		URL imgURL = new URL("http://www.google.com" + aWCIS.getIconURL());
		((SingleWeatherInfoView) findViewById(aResourceID)).setRemoteImage(imgURL);
		

		/* Convert from Celsius to Fahrenheit if necessary. */
		if (this.chk_usecelsius.isChecked()){
			((SingleWeatherInfoView) findViewById(aResourceID))
					.setTempCelcius(aWCIS.getTempCelcius());
		}else{
			((SingleWeatherInfoView) findViewById(aResourceID))
					.setTempFahrenheit(aWCIS.getTempFahrenheit());
		}
	}

	private void resetWeatherInfoViews() {
		((SingleWeatherInfoView)findViewById(R.id.weather_today)).reset();
		((SingleWeatherInfoView)findViewById(R.id.weather_1)).reset();
		((SingleWeatherInfoView)findViewById(R.id.weather_2)).reset();
		((SingleWeatherInfoView)findViewById(R.id.weather_3)).reset();
		((SingleWeatherInfoView)findViewById(R.id.weather_4)).reset();
	}
	
	public boolean onCreateOptionsMenu(Menu menu)
    {
     menu.add(1, 1, 0, "Now").setIcon(R.drawable.ic_menu_sun);;
     menu.add(1, 2, 1, "Tomorrow").setIcon(R.drawable.ic_menu_cloud);
     menu.add(1, 3, 2, "5-Day").setIcon(R.drawable.ic_menu_database);
     menu.add(1, 4, 3, "Settings").setIcon(R.drawable.ic_menu_settings);
     return true;
    }
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	        case 1:     Toast.makeText(this, "You clicked now weather", Toast.LENGTH_LONG).show();
	                            break;
	        case 2:     Toast.makeText(this, "you clicked tomorrow weather", Toast.LENGTH_LONG).show();
	                            break;
	        case 3: Toast.makeText(this, "you clicked 5 day", Toast.LENGTH_LONG).show();
	                            break;
	        case 4: Toast.makeText(this, "you clicked settings", Toast.LENGTH_LONG).show();
            					break;
	    }
	    return true;
	}
}